<?php

namespace App\Http\Controllers\Api;

use App\Libs\UcloudClient;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

class UploadController extends Controller
{
    /**
     * 上传图片到云存储
     */
    public function uploadimg($file)
    {
        try
        {
            if ( isset($file['error']) && $file['error'] != 0 )
            {
                throw new \Exception('上传文件有误!');
            }
            $ext = substr($file['name'], strpos($file['name'], '.'));
            if ( !in_array(strtolower($ext), ['.png', '.jpg', '.jpeg','.gif']) )
            {
                throw new \Exception('文件格式不正确!');
            }
            if ( $file['size'] >= 10*1024*1024 )
            {
                throw new \Exception('上传文件太大!');
            }
            $filename = date('Y/m/d/').str_random(20).$ext;
            $res = UcloudClient::minfileup($filename, $file['tmp_name']);
            if ($res['code'] != 0)
            {
                return ['code'=>0, 'msg'=>$res['msg']];
            }
            $url = 'http://file.ucloud.osv.cn/'.$filename;
            return ['code'=>1, 'data'=>$url];
        }
        catch (\Exception $e)
        {
            return ['code'=>0, 'msg'=>$e->getMessage()];
        }
    }

    /**
     * ios上传图片
     * @return array
     */
    public function iosuploadimg($file)
    {
        try
        {
            if ( isset($file['error']) && $file['error'] != 0 )
            {
                throw new \Exception('上传文件有误!');
            }

            if ( $file['size'] >= 10*1024*1024 )
            {
                throw new \Exception('上传文件太大!');
            }
            $filename = date('Y/m/d/').str_random(20).'.png';
            $res = UcloudClient::minfileup($filename, $file['tmp_name']);
            if ($res['code'] != 0)
            {
                return ['code'=>0, 'msg'=>$res['msg']];
            }
            $url = 'http://file.ucloud.osv.cn/'.$filename;
            return ['code'=>1, 'data'=>$url];
        }
        catch (\Exception $e)
        {
            return ['code'=>0, 'msg'=>$e->getMessage()];
        }
    }
}
